package cool.mtc.minghe.web.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author 明河
 */
@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketConfigurer implements WebSocketMessageBrokerConfigurer {
    private final CustomChannelInterceptor customChannelInterceptor;

    private static final ThreadPoolTaskScheduler HEARTBEAT_TASK_SCHEDULER = new ThreadPoolTaskScheduler();

    static {
        HEARTBEAT_TASK_SCHEDULER.setPoolSize(1);
        HEARTBEAT_TASK_SCHEDULER.setThreadNamePrefix("ws-heartbeat-thread");
        HEARTBEAT_TASK_SCHEDULER.initialize();
    }

    /**
     * Websocket连接端点
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 连接websocket的端点
        registry.addEndpoint("/sock-js")
                .setAllowedOriginPatterns("*")
                .withSockJS();
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*");
    }

    /**
     * 配置消息代理
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端订阅的前缀
        registry.enableSimpleBroker("/topic")
                .setHeartbeatValue(new long[]{0, 60 * 1000L})
                .setTaskScheduler(HEARTBEAT_TASK_SCHEDULER);
        // 客户端向服务端发送消息要求的前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 给指定用户发送消息要求的前缀
        registry.setUserDestinationPrefix("/chat");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(customChannelInterceptor);
    }

}
